//
//  WSSettingController.m
//  BaseProject
//
//  Created by karong on 2023/8/7.
//

#import "WSSettingController.h"
#import "CTMediator+WSUserCenterAction.h"
#import "WSSettingRequest.h"
#import "AppDelegate.h"
#import "WSSettingFootView.h"
#import <SDWebImage/SDWebImage.h>
#import "WSLanguage.h"

@interface WSSettingController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, WSSettingFootViewDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (nonatomic, strong) NSArray * dataArray;

@end

@implementation WSSettingController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)delUsercharonTV_Request {
    [WSSettingRequest delUserWithSuccess:^{
        [((AppDelegate*)([UIApplication sharedApplication].delegate)) initMainPage];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

///個人信息
- (void)userInfoAction {
    if (appUserCenter.isLogin) {
        UIViewController *userInfoVC = [[CTMediator sharedInstance]ct_showcharonTV_UserInfoWithUser:appUserCenter];
        [self.navigationController pushViewController:userInfoVC animated:YES];
    }
    else {
        [((AppDelegate*)([UIApplication sharedApplication].delegate)) initMainPage];
    }
    
}

///賬號與安全
- (void)accountAction {
    UIViewController * target = [[CTMediator sharedInstance]ct_showcharonTV_Account];
    [self.navigationController pushViewController:target animated:YES];
}

///自動購買
- (void)autoPayAction {
    appConfig.isAutoPay = !appConfig.isAutoPay;
    self.dataArray = nil;
    [self.listView reloadData];
}

///清除緩存
- (void)clearCacheAction {
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
    [WSToast simple:APPLocalized(@"操作成功")];
    self.dataArray = nil;
    [self.listView reloadData];
}

///用戶協議
- (void)userAgreementAction {
    UIViewController * target = [[CTMediator sharedInstance]ct_showWebWithUrl:API_CHARONTV_AGREEMENT_USER titleStr:APPLocalized(@"用戶協議") showNav:YES closeHandle:^{}];
    [self.navigationController pushViewController:target animated:YES];
}

///隱私政策
- (void)privacyAction {
    UIViewController * target = [[CTMediator sharedInstance]ct_showWebWithUrl:API_CHARONTV_AGREEMENT_PRIVACY titleStr:APPLocalized(@"隱私政策") showNav:YES closeHandle:^{}];
    [self.navigationController pushViewController:target animated:YES];
}

///檢查更新
- (void)checkUpdataAction {
    if (appConfig.startConfig.ios_upgrade_popup_switch == 1) {
        UIViewController * target = [[CTMediator sharedInstance]ct_showcharonTV_Updata];
        target.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        target.modalPresentationStyle = UIModalPresentationCustom;
        [self presentViewController:target animated:YES completion:nil];
    }
    else {
        [WSToast simple:APPLocalized(@"當前已是最新版本")];
    }
}

///賬號註銷
- (void)delUserAction {
    UIViewController * target = [[CTMediator sharedInstance]ct_showcharonTV_DelUertAlterWithTitle:APPLocalized(@"註銷賬號確認？") content:APPLocalized(@"註銷賬號將清空所有信息和數據，歷史交易產生的權益，及未使用剧豆將視為自動放棄，請確認是否註銷？") confirm:APPLocalized(@"確認註銷") confirmHandle:^{
        [self delUsercharonTV_Request];
    } cancel:@""];
    target.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;  
    target.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:target animated:YES completion:nil];
}

///切换语言
-(void)checkChangeLaungAction{
    //NSLocalizedString
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:APPLocalized(@"請選擇需要切換的語言") message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *one = [UIAlertAction actionWithTitle:APPLocalized(@"简体中文") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [WSLanguage setUserLanguageType:1];
    }];
    UIAlertAction *one2 = [UIAlertAction actionWithTitle:APPLocalized(@"繁體中文") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [WSLanguage setUserLanguageType:3];
    }];
    UIAlertAction *one3 = [UIAlertAction actionWithTitle:APPLocalized(@"English") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [WSLanguage setUserLanguageType:2];
        
    }];
    UIAlertAction *one4 = [UIAlertAction actionWithTitle:APPLocalized(@"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:one];
    [alert addAction:one2];
//    [alert addAction:one3];
    [alert addAction:one4];
    [self presentViewController:alert animated:YES completion:nil];
    
}
///退出登錄
- (IBAction)logOutAction {
    [appUserCenter logOut];
    [((AppDelegate*)([UIApplication sharedApplication].delegate)) initMainPage];
    [WSToast simple:APPLocalized(@"退出成功")];
}
#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"kcell" forIndexPath:indexPath];
    NSDictionary * dic = self.dataArray[indexPath.row];
    UILabel * label = [cell viewWithTag:101];
    label.text = APPLocalized(dic[@"title"]);
    UILabel * subLabel = [cell viewWithTag:102];
    subLabel.text = dic[@"subTitle"];
    UIButton * updataBtn = [cell viewWithTag:103];
    if ([@"檢查更新" isEqualToString:dic[@"title"]] && appConfig.startConfig.ios_upgrade_popup_switch == 1) {
        updataBtn.hidden = NO;
    }
    else {
        updataBtn.hidden = YES;
    }
    UIImageView * image = [cell viewWithTag:104];
    image.image = WSIMG(dic[@"image"]);
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeZero;
    size.width = WSScreenWidth;
    size.height = 54;
    return size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary * dic = self.dataArray[indexPath.row];
    SEL sel = NSSelectorFromString(dic[@"sel"]);
    if ([self respondsToSelector:sel]) {
        [self performSelector:sel withObject:nil];
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        WSSettingFootView * settingFootView;
        if (!settingFootView) {
            settingFootView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"WSSettingFootView" forIndexPath:indexPath];
            settingFootView.delegate = self;
        }
        return settingFootView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    CGSize size = CGSizeZero;
    size.width = WSScreenWidth;
    size.height = 44 + 82;
    return size;
}

#pragma mark WSSettingFootViewDelegate
- (void)settingFootViewLogOutAction {
    [self logOutAction];
}

- (void)settingFootViewDelUserAction {
    [self delUserAction];
}

- (NSArray *)dataArray {
    if (!_dataArray) {
        NSString *lanStr = @"繁體中文";
        if (appConfig.laType == 1){
            lanStr = @"简体中文";
        }else if (appConfig.laType == 2){
            lanStr = @"English";
        }
        _dataArray = @[@{@"title":@"個人信息",
                         @"subTitle":@"",
                         @"image":@"icon_more",
                         @"sel":@"userInfoAction"},
                       @{@"title":@"賬號與安全",
                         @"subTitle":@"",
                         @"image":@"icon_more",
                         @"sel":@"accountAction"},
                       @{@"title":@"自動購買",
                         @"subTitle":@"",
                         @"image":(appConfig.isAutoPay)?@"ic_setup_open":@"ic_setup_close",
                         @"sel":@"autoPayAction"},
                       @{@"title":@"清除緩存",
                         @"subTitle":WSEmptyStr([self cacheSize]),
                         @"image":@"icon_more",
                         @"sel":@"clearCacheAction"},
                       @{@"title":@"用戶協議",
                         @"subTitle":@"",
                         @"image":@"icon_more",
                         @"sel":@"userAgreementAction"},
                       @{@"title":@"隱私政策",
                         @"subTitle":@"",
                         @"image":@"icon_more",
                         @"sel":@"privacyAction"},
                       @{@"title":@"檢查更新",
                         @"subTitle":[NSString stringWithFormat:@"v%@", [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"]],
                         @"image":@"icon_more",
                         @"sel":@"checkUpdataAction"},
                       @{@"title":@"切換語言",
                         @"subTitle":lanStr,
                         @"image":@"icon_more",
                         @"sel":@"checkChangeLaungAction"}];
    }
    return _dataArray;
}

- (NSString *)cacheSize {
    NSUInteger size = [[SDImageCache sharedImageCache] totalDiskSize];
    NSString *cacheStr = [WSTools fileSizeWithInterge:size];
    return cacheStr;
}


@end
